<template>
  <div class="new-bind-phone">
    <div class="main-box">
      <div class="center-form">
        <el-form
          ref="registerFromData"
          class="register-form"
          :rules="registerFormRules"
          :model="registerFromData"
          label-width="80px"
        >
          <el-form-item label="手机号：" prop="phone">
            <el-input
              class="phone-input"
              maxlength="11"
              type='tel'
              placeholder="请输入账号"
              v-model="registerFromData.phone"
            />
          </el-form-item>
          <el-form-item label="密码：" prop="password">
            <el-input
              v-model.trim="registerFromData.password"
              placeholder="请设置6-16位字母、数字"
              clearable
              maxlength="20"
              class="password-input"
              show-password
            />
          </el-form-item>
          <el-form-item label="验证码：" prop="verificationCode">
            <div class="capcha-corver">
              <el-input
                v-model.trim="registerFromData.verificationCode"
                placeholder="请输入手机验证码"
                maxlength="6"
                class="capcha-input"
              >
                <el-button
                 v-if="codeShow"
                  class="capcha-button"
                  type="primary"
                  slot="suffix"
                  :disabled="sendCodeDiabled"
                  @click="sendCode"
                  :loading="codeLoading"
                  >{{ sendCodeTitle }}</el-button>
                  <el-button
                  v-if="timoutShow"
                  class="capcha-button"
                  type="primary"
                  slot="suffix"
                  :disabled="sendCodeDiabled"
                  >{{ time }}s</el-button>
              </el-input>
            </div>
          </el-form-item>
          <el-form-item>
            <div>
              <dragBox
                ref="dragVerify"
                @dragStatus="dragStatus"
                :index="1"
              >
              </dragBox>
            </div>
          </el-form-item>
          <el-form-item>
            <el-checkbox v-model="registerFromData.agreeToRegister" class="agreement-checkbox"
              >已阅读并同意</el-checkbox
            >
            <span class="service-agreement" @click="showService('PLATFORM_SERVICE')"
              >《服务协议》</span
            >
            <span class="privacy-agreement" @click="showPrivacy('PRIVACY_POLICY')"
              >《隐私政策》</span
            >
          </el-form-item>
          <el-form-item>
            <div class="button-corver">
              <el-button class="goback" @click="goBack">返回</el-button>
              <el-button class="submit" @click="submitResult">完成</el-button>
            </div>
          </el-form-item>
        </el-form>
      </div>
    </div>
     <el-dialog
      :visible.sync="serviceAgreementVisible"
      width="60%"
      :show-close="false"
      :close-on-click-modal="false"
      >
      <span v-html="agreementData.agreementContent">{{agreementData.agreementContent}}</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="serviceAgreementVisible = false">取 消</el-button>
        <el-button type="primary" @click="readAgreement(agreementData.id)">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import cookie from 'js-cookie';
import {phone} from '@const/formValidate.js'
import md5 from 'js-md5'
import {
  sendRegistVerificationCode,
  getByAgreementCodeList,
  simpleRegisterUser,
  initDragBox
} from '@const/api_staffCenter.js';
import {Encrypt} from '@const/utils.js'
import dragBox from '../../moduleComponents/login/hospital/drag.vue'
export default {
  name: 'newBindPhone',
  layout: 'login',
  components: {
    dragBox
  },
  data() {
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入账号'))
      } else {
        if (!/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$/.test(value)) {
          callback(new Error('密码为6-16位数字字母组合'))
          return false
        }
        // if (this.registerFromData.account !== '') {
        //   this.$refs.registerFromData.validateField('account')
        // }
        callback()
      }
    }
    return {
      registerFromData: {
        phone: '',
        password: '',
        verificationCode: '',
        agreeToRegister: ''
      },
      registerFormRules: {
        phone: phone(),
        verificationCode: [
          {required: true, message: '请输入验证码', trigger: 'blur'},
          {
            pattern: /^[0-9]{6}$/,
            message: '请输入6位数字验证码',
            trigger: 'blur'
          }
        ],
        pwd: [{required: true, validator: validatePass, trigger: 'blur'}]
      },
      sendCodeDiabled: false,
      codeLoading: false,
      sendCodeTitle: '获取验证码',
      timout: '',
      codeShow: true,
      timoutShow: false,
      time: 60,
      serviceAgreement: '', // 服务协议
      agreementName: '',
      serviceAgreementVisible: false,
      privacyAgreementVisible: false,
      agreementCodeList:[],
      agreementData: '',
      agreementList:[],
      isChrome: this.myBrowser() === 'Chrome',
      isWinXP: this.detectOS() === 'WinXP',
      dragStatusData: false,
      sendCodeClick: false
    }
  },
  methods: {
    dragStatus(val) {
      console.log('349val', val)
      this.dragStatusData = val
    },
    sendCode() {
      this.sendCodeClick = true
      this.$axios({
        url: sendRegistVerificationCode,
        method: 'post',
        data: {
          phone: this.registerFromData.phone,
          source: 'm_pc_web'
        }
      })
        .then(res => {
          if (res.data.code === '0') {
            this.codeShow = false
            this.timoutShow = true
            this.timout = setInterval(()=>{
              let time = this.time;
              time = time - 1
              this.time = time
              if (this.time === 0) {
                clearTimeout(this.timout)
                this.time = false
                this.codeShow = true
                this.time = 60
                this.timoutShow = false
              }
            },1000)
            this.$message({type: 'success', message: '验证码发送成功！'})
          }
        })
        .catch(err => {
          // reject(err);
        });
    },
    getagreementCodeList() {
      this.$axios({
        url: getByAgreementCodeList,
        method: 'get',
        data: {}
      })
        .then(res => {
          if (res.data.code === '0') {
            this.agreementCodeList = res.data.payload || []
            this.agreementCodeList.map( a => {
              this.agreementList.push(a.id)
            })
            console.log('======this.agreementList:', this.agreementList)
          }
        })
        .catch(err => {
          // reject(err);
        });
    },
    readAgreement(id) {
      if (!this.agreementList.includes(id)) {
        this.agreementList.push(id)
      }
      this.serviceAgreementVisible = false
      console.log('==this.agreementList:', this.agreementList)
    },
     // 打开服务协议
    showService(agreementType) {
      console.log('=====agreementType:', agreementType)
      this.agreementData = this.agreementCodeList.filter((a) => {
          return a.agreementCode === agreementType
        }
      )
      this.agreementData = this.agreementData[0]
      this.serviceAgreementVisible = true;
    },
    // 隐私政策
    showPrivacy(agreementType ) {
      this.agreementData = this.agreementCodeList.filter((a) => {
          return a.agreementCode === agreementType
        }
      )
      this.agreementData = this.agreementData[0]
      this.serviceAgreementVisible = true;
    },
    goBack() {
      this.$router.push({
        path: this.$PATH_CONST.login_page
      })
    },
    submitResult() {
      let _this = this
      let randomCode = md5 (`${this.$store.state.randomCode}${this.$store.state.moveTime}m_pc_web`) 
      console.log('======randomCode:', randomCode)
      if (!this.isChrome) {
        return false
      }
      if (!this.dragStatusData) {
        this.$message.warning('请按住滑块拖放到最右边')
        return false
      }
      console.log('====0000=====')
      this.$refs['registerFromData'].validate(valid => {
        console.log('========valid', valid)
        if (!this.registerFromData.agreeToRegister) {
          this.$message({type: 'success', message: '请阅读协议'})
          return false
        }
        let parms = JSON.parse(JSON.stringify(this.registerFromData))
        parms.source = 'm_pc_web'
        parms.code = cookie.get('wechatCode') || ''
        parms.randomCode = randomCode
        parms.password = md5(parms.password)
        parms.agreementList = this.agreementList
        if (!this.sendCodeClick) {
          this.$message({type: 'success', message: '请获取验证码'})
          return false
        }
        if (valid) { 
          this.$axios({
            url: simpleRegisterUser,
            method: 'post',
            data: parms
          })
            .then(res => {
              if (res.data.code === '0') {
                this.$message({type: 'success', message: '绑定成功'})
                this.$store.commit('login', res.data.payload || {});
                cookie.remove('wechatCode')
                // window.location.href = '/#/business/'
                let curryCompanyId = cookie.get('companyId') || ''
                if (curryCompanyId === '0') {
                  window.location.href = '/#/business/'
                } else {
                  window.location.href = '/'
                }
              }
              if (res.data.code !== 0) {
                this.$refs.dragVerify.reset() //重置滑动验证码
                this.getRandomCode()
                this.dragStatusData = false
                this.sendCodeClick = false
                this.registerFromData.verificationCode = ''
              }
            })
            .catch(err => {
              console.log('=====err:', err)
              this.getRandomCode()
              // TODO 异常处理
              this.$refs.dragVerify.reset() //重置滑动验证码
              this.dragStatusData = false
              this.sendCodeClick = false
              this.registerFromData.verificationCode = ''
            });
        }
      })
    },
    getRandomCode () {
      let timestamp = new Date().getTime()
      let source = 'm_pc_web'
      this.$axios({
        url: initDragBox,
        method: 'post',
        data: {
          timestamp: timestamp,
          source: source
        }
      })
        .then(res => {
          console.log('======res.data.payload:', res.data.payload)
          this.$store.commit('randomCode', res.data.payload)
          console.log('======res.data.payload:', this.$store.state.randomCode)
        })
        .catch(err => {
          reject(err);
        });
    },
     // 获取浏览器类型
    myBrowser() {
      var userAgent = navigator.userAgent // 取得浏览器的userAgent字符串
      var isOpera = userAgent.indexOf('Opera') > -1
      console.log('当前浏览器信息：', userAgent)
      if (isOpera) {
        return 'Opera'
      } // 判断是否Edge浏览器
      if (userAgent.indexOf('Edge') > -1) {
        return 'Edge'
      } // 判断是否Opera浏览器
      if (userAgent.indexOf('Firefox') > -1) {
        return 'FF'
      } // 判断是否Firefox浏览器
      if (userAgent.indexOf('Chrome') > -1) {
        return 'Chrome'
      }
      if (userAgent.indexOf('Safari') > -1) {
        return 'Safari'
      } // 判断是否Safari浏览器
      if (
        userAgent.indexOf('compatible') > -1 &&
        userAgent.indexOf('MSIE') > -1 &&
        !isOpera
      ) {
        return 'IE'
      } // 判断是否IE浏览器
      if (userAgent.toLowerCase().indexOf('se 2.x') > -1) {
        return 'SOUGOU'
      }
    },
    detectOS() {
      var userAgent = navigator.userAgent
      var isWin =
        navigator.platform == 'Win32' || navigator.platform == 'Windows'
      var isMac =
        navigator.platform == 'Mac68K' ||
        navigator.platform == 'MacPPC' ||
        navigator.platform == 'Macintosh' ||
        navigator.platform == 'MacIntel'
      if (isMac) return 'Mac'
      var isUnix = navigator.platform == 'X11' && !isWin && !isMac
      if (isUnix) return 'Unix'
      var isLinux = String(navigator.platform).indexOf('Linux') > -1
      if (isLinux) return 'Linux'
      if (isWin) {
        var isWin2K =
          userAgent.indexOf('Windows NT 5.0') > -1 ||
          userAgent.indexOf('Windows 2000') > -1
        if (isWin2K) return 'Win2000'
        var isWinXP =
          userAgent.indexOf('Windows NT 5.1') > -1 ||
          userAgent.indexOf('Windows XP') > -1
        if (isWinXP) return 'WinXP'
        var isWin2003 =
          userAgent.indexOf('Windows NT 5.2') > -1 ||
          userAgent.indexOf('Windows 2003') > -1
        if (isWin2003) return 'Win2003'
        var isWinVista =
          userAgent.indexOf('Windows NT 6.0') > -1 ||
          userAgent.indexOf('Windows Vista') > -1
        if (isWinVista) return 'WinVista'
        var isWin7 =
          userAgent.indexOf('Windows NT 6.1') > -1 ||
          userAgent.indexOf('Windows 7') > -1
        if (isWin7) return 'Win7'
        var isWin7 =
          userAgent.indexOf('Windows NT 6.2') > -1 ||
          userAgent.indexOf('Windows 8') > -1
        if (isWin7) return 'Win8'
        var isWin7 =
          userAgent.indexOf('Windows NT 10.0') > -1 ||
          userAgent.indexOf('Windows 10') > -1
        if (isWin7) return 'Win10'
      }
      return 'other'
    },
  },
  mounted() {
    this.registerFromData.phone = cookie.get('wechatRegisterPassword') || ''
    this.getRandomCode()
    this.getagreementCodeList()

  },
  created() {
    this.$store.commit('setLoginTitle', '微信注册并登录')
  }
}
</script>
<style lang="less">
.new-bind-phone {
  font-family: PingFangSC-Regular;
  background:
    #f4f6fb
    url('../../../m-front-common/pc/assets/img/home/registerbg1.png') no-repeat
    100% 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  .main-box {
    min-width: 460px;
    min-height: 320px;
    width: 822px;
    height: 505px;
    background: white;
    display: flex;
    justify-content: center;
    align-items: center;
    .center-form {
      .service-agreement,
      .privacy-agreement {
        font-size: 12px;
        color: #4d84ff;
        letter-spacing: 0;
        line-height: 17px;
        &:hover {
          cursor: pointer;
        }
      }
      .agreement-checkbox {
        &:hover {
          cursor: pointer;
        }
      }
      .capcha-button {
        width: 120px;
        height: 38px;
        background: #f4f4f4;
        border-left: 1px solid #ccc;
        border-radius: 0 2px 2px 0;
        border-top: none;
        border-right: none;
        border-bottom: none;
        font-size: 14px;
        color: #666;
        letter-spacing: 0;
        margin-right: -4px;
      }
      .button-corver {
        width: 330px;
        display: flex;
        justify-content: space-around;
        .goback {
          width: 114px;
          height: 42px;
          background: #f4f4f4;
          border: 1px solid #ccc;
          border-radius: 4px;
          border-radius: 4px;
          font-size: 16px;
          color: #666;
          letter-spacing: 0;
        }
        .submit {
          width: 114px;
          height: 42px;
          background: #4d84ff;
          border-radius: 4px;
          font-size: 16px;
          color: #fff;
          letter-spacing: 0;
        }
      }
    }
  }
  // element表单重置
  .el-input__inner {
    width: 330px;
    height: 40px;
    border-radius: 2px;
    border: 1px solid #ccc;
  }
  .el-checkbox__label {
    font-size: 12px;
  }
  .el-dialog__header{
    display: none
  }
}
</style>
